package cn.imvc.app.models;

import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import cn.imvc.app.entities.Express;
import cn.imvc.app.entities.Seller;
import cn.imvc.app.repositories.ExpressRepository;
import cn.imvc.core.ModelUtil;
import cn.imvc.data.domain.ViewRequest;

/**
 * 
 * @author zhy
 * @date 2016年8月2日下午4:02:01
 *
 */
@Service
public class ExpressModelImpl implements ExpressModel{

	@Autowired
	ExpressRepository expressRepository;
	@Autowired
	ExpressFeeModel expressFeeModel;
	@Autowired
	RefRelationModel refRelationModel;
	
	public Page<Express> find(ViewRequest viewRequest) {
		
		return expressRepository.findAll(ModelUtil.OrderByIdDesc(viewRequest));
	}

	public Express get(int id) {
		
		return expressRepository.getOne(id);
	}

	public int save(int sellerId,Express express){
		Seller seller = express.getSeller();
		String code = express.getCode();
		String name = express.getName();
		List<Express> ec = expressRepository.getBySellerAndCode(seller,code);
		List<Express> en = expressRepository.getBySellerAndName(seller,name);
		if(ec.size()>0){
			return 0;
		}else if(en.size()>0){
			return -1;
		}
		expressRepository.saveAndFlush(express);
		return 1;
	}

	public int update(int id,int sellerId,Express express) {
		Express loadExpress = expressRepository.getOne(id);
		Seller seller = express.getSeller();
		String code = express.getCode();
		String name = express.getName();
		List<Express> ec = expressRepository.getBySellerAndCode(seller,code);
		List<Express> en = expressRepository.getBySellerAndName(seller,name);
		if(ec.size()>0&&!code.equals(loadExpress.getCode())){
			return 0;
		}else if(en.size()>0&&!name.equals(loadExpress.getName())){
			return -1;
		}
		BeanUtils.copyProperties(express, loadExpress, new String[]{"id"});
		expressRepository.saveAndFlush(loadExpress);
		return 1;
	}
	
	public String delete(int id) {
		String result = refRelationModel.deleteDateCheck("Express", "id", id);
		if(result.equals("")){
		expressRepository.delete(id);
		return "";
		}else{
			return result;
		}
	}

	public void deleteBatch(int[] ids) {
		
		for (int id : ids) {
			
		expressRepository.delete(id);
		}
	}


}
